package cn.wind.xboot.module.web.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.framework.domain.PageVo;
import cn.wind.xboot.logic.entity.VegetableMarket;
import cn.wind.xboot.logic.service.IVegetableMarketService;
import cn.wind.xboot.module.web.enums.MarketModelEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 *菜市场管理
 * @author WangHao
 * @date 2018-12-26
 */
@Slf4j
@RequestMapping("vegetableMarket")
@Controller
public class VegetableMarketController {
    @Autowired
    private IVegetableMarketService vegetableMarketService;

    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
    /**
     * 菜市场-添加
     * @param vegetableMarket
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ApiResult add(VegetableMarket vegetableMarket){
        vegetableMarketService.saveOrUpdate(vegetableMarket);
        return ApiResult.Custom().success("添加成功!");
    }
    /**
     * 菜市场-删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ApiResult delete(VegetableMarket vegetableMarket){
        vegetableMarketService.removeById(vegetableMarket.getId());
        return ApiResult.Custom().success("删除成功!");
    }

    /**
     * 菜市场-修改
     */
    @RequestMapping("/modify")
    @ResponseBody
    public ApiResult modify(VegetableMarket vegetableMarket){
        vegetableMarketService.saveOrUpdate(vegetableMarket);
        return ApiResult.Custom().success("修改成功!");
    }

    /**
     * 菜市场-列表展示及条件查询
     */
    @RequestMapping("/list")
    @ResponseBody
    public ApiResult list(PageVo pageVo,String province,String city,String district){
        Map<String,Object> map = Maps.newHashMap();
        map.put("province", province);
        map.put("city",city);
        map.put("district",district);
        IPage<VegetableMarket> page = vegetableMarketService.findByCondition(pageVo.init(),map);
        return ApiResult.Custom().success("查询成功").add(page);
    }

    /**
     * 菜市场-查询所有菜市场(不分页)
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public ApiResult findAll(){
        List<VegetableMarket> list = vegetableMarketService.findAll();
        return ApiResult.Custom().success().add(list);
    }
    /**
     * 菜市场-详情
     */
    @RequestMapping("/info")
    @ResponseBody
    public ApiResult info(Long id){
        VegetableMarket vegetableMarket = vegetableMarketService.getById(id);
        return ApiResult.Custom().success().add(vegetableMarket);
    }

    /**
     * 菜市场-导入
     */
    @RequestMapping("importXls")
    @ResponseBody
    public ApiResult importXls(MultipartHttpServletRequest multipart) throws IOException {
        //记录导入
        MultipartFile file = multipart.getFile("file");
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Map<String, Object>> readAll = reader.readAll();
        List<VegetableMarket> vegetableMarkets = new ArrayList<>();
        for (Map map : readAll) {
            VegetableMarket market = new VegetableMarket();
            market.setName(map.get( MarketModelEnum.name.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.name.getTypeName()).toString());
            market.setProvince(map.get(MarketModelEnum.province.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.province.getTypeName()).toString());
            market.setCity(map.get(MarketModelEnum.city.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.city.getTypeName()).toString());
            market.setDistrict(map.get(MarketModelEnum.district.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.district.getTypeName()).toString());
            market.setAddress(map.get(MarketModelEnum.address.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.address.getTypeName()).toString());
            market.setAddress(map.get(MarketModelEnum.address.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.address.getTypeName()).toString());
            vegetableMarkets.add(market);
        }
        vegetableMarketService.saveOrUpdateBatch(vegetableMarkets);
        return ApiResult.Custom().success("导入完成");
    }

    /**
     * 菜市场管理-导入模板下载
     */
    @RequestMapping("download")
    @ResponseBody
    public void download(HttpServletRequest req, HttpServletResponse resp) {
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("excel/detail.xlsx");
            System.out.println("文件流："+in.available());
            req.setCharacterEncoding("UTF-8");
            //获取要下载的文件名
            String name = "企业导入模板.xlsx";
            //第一步：设置响应类型
            //应用程序强制下载
            resp.setContentType("application/force-download");
            //设置响应头，对文件进行url编码
            name = URLEncoder.encode(name, "UTF-8");
            resp.setHeader("Content-Disposition", "attachment;filename=" + name);
            resp.setContentLength(in.available());

            //第三步：老套路，开始copy
            OutputStream out = resp.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 菜市场导出
     * @param id
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(Long id, HttpServletResponse response) throws Exception {
       /**/ String marketName = "菜市场";
        VegetableMarket vegetableMarket = vegetableMarketService.getById(id);
        if (vegetableMarket != null) {
            marketName = vegetableMarket.getName();
        }
        List<VegetableMarket> marketList = vegetableMarketService.findAll();
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet( "菜市场记录");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        // 创建一个居中格式
        style.setAlignment( HorizontalAlignment.CENTER);

        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("序号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("菜市场名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("所在位置");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("排序");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("添加时间");
        cell.setCellStyle(style);
        int i = 1;
        for (VegetableMarket market : marketList) {
            row = sheet.createRow(i);
            // 第四步，创建单元格，并设置值
            cell = row.createCell((short) 0);
            cell.setCellValue(i);
            cell.setCellStyle(style);
            cell = row.createCell((short) 1);
            cell.setCellValue(market.getAddress());
            cell.setCellStyle(style);
            cell = row.createCell((short) 2);
            cell.setCellValue(market.getSort());
            cell.setCellStyle(style);
            cell = row.createCell((short) 3);
            if (market.getCreateTime() != null) {
                cell.setCellValue(sdf2.format(market.getCreateTime()));
            } else {
                cell.setCellValue("——");
            }
            cell.setCellStyle(style);
            i++;
        }

        //让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < 6; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            if (colNum == 0) {
                sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
            } else {
                sheet.setColumnWidth(colNum, (columnWidth + 10) * 256);
            }
        }

        // 第六步，将文件存到指定位置
        try {
            Date date = new Date();
            String fileName ="报名记录_" + date.getTime();
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
